package com.yycx.module.bus.provider.handler.orderdetails;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.module.bus.client.entity.BusOrder;
import com.yycx.module.bus.client.entity.BusOrderDetails;
import com.yycx.module.bus.provider.service.BusOrderDetailsService;
import com.yycx.module.bus.provider.service.BusOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单商品列表扩展
 *
 * @author zyf
 */
@Component("orderDrugsHandler")
public class OrderDrugsHandler implements PageInterceptor<BusOrderDetails> {


    @Override
    public List<EntityMap> complete(CriteriaQuery<BusOrderDetails> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap map : result) {
            Long orderDetailsId = map.getLong("orderDetailsId");
            Integer customBondType = map.getInt("customBondType");
            if (customBondType.equals(1) || customBondType.equals(3) || customBondType.equals(2) || customBondType.equals(6)) {
                BigDecimal orderCustomBond = map.getBigDecimal("customBond");
                if (FlymeUtils.isNotEmpty(orderCustomBond)) {
                    map.put("customBond", orderCustomBond);
                } else {
                    map.put("customBond", "-");
                }
            }
            //预付款情况计算未回款金额
            if (customBondType.equals(7)) {
                Long orderId = map.getLong("orderId");
                BusOrder busOrder = orderService.getById(orderId);
                BigDecimal totalSaleAmount = orderDetailsService.totalSaleAmount(orderId);
                //预付款金额
                BigDecimal yfkAmount = busOrder.getTakeAmount();
                BigDecimal saleAmount = map.getBigDecimal("saleAmount");
                BigDecimal ratio = saleAmount.divide(totalSaleAmount, 4, BigDecimal.ROUND_HALF_UP);
                BigDecimal returnAmount = yfkAmount.multiply(ratio).setScale(2);
                if (FlymeUtils.isNotEmpty(yfkAmount)) {
                    map.put("returnAmount", returnAmount);
                    //计算未回款金额
                    map.put("noReturnAmount", saleAmount.subtract(returnAmount));
                } else {
                    map.put("returnAmount", "-");
                }
            }



        }
        return result;
    }




    final BusOrderService orderService;
    final BusOrderDetailsService orderDetailsService;

    @Autowired
    public OrderDrugsHandler(BusOrderService orderService, BusOrderDetailsService orderDetailsService) {
        this.orderService = orderService;
        this.orderDetailsService = orderDetailsService;
    }

}
